<?php
/**
 * Created by paperphp
 * User: 22071
 * Date: 2019/6/26
 * Email: <zhendongdong@foxmail.com>
 */

namespace paper\http;

use paper\constraint\Middleware;
use paper\http\response\Response;

class MiddlewareManager
{

    //待处理的中间件队列
    protected $queue = [];
    protected $middleware = [];
    protected \Closure $destination;
    protected $app;

    public function __construct()
    {
    }


    public function register($middleware)
    {
        $this->middleware = $middleware;
    }


    public function then(Request $request, \Closure $destination)
    {
        $this->destination = $destination;
        return call_user_func($this->resolve($request));
    }


    /**
     * @param $middleware
     */
    public function add(string $middleware)
    {
        $this->queue[$middleware] = $middleware;
    }

    /**
     * 取消注册的中间件
     * @param array $middlewares
     */
    public function unregister(array $middlewares)
    {
        foreach ($middlewares as $middleware)
            unset($this->queue[$middleware]);
    }

    /**
     * @param array $middleware
     */
    public function import(array $middleware)
    {
        foreach ($middleware as $item) {
            $this->add($item);
        }
    }

    /**
     * 开始消费中间件
     * @return \Closure
     */
    public function resolve(Request $request): \Closure
    {
        return function () use ($request): Response {
            $middleware = array_shift($this->queue);

            if ($middleware == null) {
                $destination = $this->destination;
                return $destination($request);
            }
            $abstract = new $middleware();
            if ($abstract instanceof Middleware) {
                return $abstract->onBoot($request, $this->resolve($request));
            } else {
                return $this->resolve($request)($request);
            }

        };
    }
}